<template>
  <van-popup
    v-model="showDialog"
    class="payment-dialog"
    position="bottom"
    :close-on-click-overlay="false"
    closeable
    round
  >
    <h1>在线支付</h1>
    <h2>
      <price :value="price" />
    </h2>
    <div class="countdown">
      <div class="countdown-container">
        <span class="countdown-title">支付剩余时间:</span>
        <van-count-down :time="countdown" />
      </div>
    </div>
    <van-radio-group
      v-model="paymode"
      checked-color="#ff6600"
      class="payment-paymodes"
    >
      <van-cell-group>
        <van-cell
          v-for="(item, index) in paymodes"
          :key="index"
          :icon="item.icon"
          :title="item.label"
          :label="item.description"
          @click="paymode = item.name"
        >
          <van-radio
            slot="right-icon"
            :name="item.name"
          />
        </van-cell>
      </van-cell-group>
    </van-radio-group>

    <van-button
      block
      round
      type="warning"
      @click="onPayment"
    >确认付款</van-button>
  </van-popup>
</template>

<script>
import {
  Icon,
  Popup,
  Button,
  Cell,
  CellGroup,
  Radio,
  RadioGroup,
  CountDown
} from 'vant'
import Price from '@/components/price'

export default {
  name: 'CheckGoodsCard',
  components: {
    Price,
    [Icon.name]: Icon,
    [Popup.name]: Popup,
    [Button.name]: Button,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [Radio.name]: Radio,
    [RadioGroup.name]: RadioGroup,
    [CountDown.name]: CountDown
  },
  model: {
    prop: 'showPayment',
    event: 'close'
  },
  props: {
    showPayment: false,
    orderId: {
      type: Number,
      default: 0
    }
  },
  computed: {
    showDialog: {
      get: function () {
        return this.showPayment
      },
      set: function (value) {
        this.$emit('close', value)
      }
    }
  },
  watch: {
    showPayment (c, o) {
      console.log(c, o)
      if (c === true) {
        this.onLoad()
      }
    },
    paymodes (c, o) {
      var newArr = c.filter(item => {
        return item.default
      })
      console.log(newArr)
      if (newArr.length > 0) {
        this.paymode = newArr[0].name
      } else {
        this.paymode = c[0].name
      }
    }
  },
  data () {
    return {
      paymode: 'wechat',
      price: 0,
      countdown: 30 * 60 * 60 * 1000,
      order_no: '',
      paymodes: [
        {
          label: '微信支付',
          description: '亿万用户的选择，更快更安全',
          name: 'wechat',
          default: true,
          icon: 'wechat'
        },
        {
          label: '支付宝',
          description: '支付订单，赢大额现金红包',
          name: 'alipay',
          default: false,
          icon: 'alipay'
        }
      ]
    }
  },
  methods: {
    onLoad () {
      console.log(this.paymode, this.orderId)
      this.$http.trade
        .getPaymentOrder({
          scope: 'shop',
          order_id: this.orderId
        })
        .then(res => {
          const { data } = res
          if (res.data) {
            this.order_no = data.order_no
            this.price = data.price
            this.countdown = data.countdown
            this.paymodes = data.paymodes
          }
          console.log(res)
        })
        .catch(e => {
          console.log(e)
        })
    },
    onPayment () {
      console.group('Payment')
      console.log('[paymode]', this.paymode)
      console.log('[orderId]', this.orderId)

      let inWechatBrowse = this.$store.state.authorize.connect
        ? this.$store.state.authorize.connect
        : false
      console.log('[inWechatBrowse]', inWechatBrowse)

      let params = {
        scope: 'shop',
        paymode: this.paymode,
        order_id: this.orderId,
        connect_id: inWechatBrowse.id
      }

      console.log('[orderId]', params)
      this.$http.trade
        .createPaymodeOrder(params)
        .then(res => {
          console.log(res)
          const { data } = res
          if (data.wechat) {
            this.wxPay(data.wechat)
          } else if (data.alipay) {
            console.log(data.alipay)
            this.$router.push({
              path: '/trade/payment/alipay',
              query: { form: res.data.alipay }
            })
          }
        })
        .catch(e => {
          console.log(e)
        })
    },
    aliPay (form) {
      const div = document.createElement('div')
      div.id = 'alipay'
      div.innerHTML = form
      document.body.appendChild(div)
      document.querySelector('#alipay').children[0].submit() // 执行后会唤起支付宝
    },
    wxPay (data) {
      var vm = this
      // 下面是解决WeixinJSBridge is not defined 报错的方法
      if (typeof WeixinJSBridge === 'undefined') {
        // 微信浏览器内置对象。参考微信官方文档
        if (document.addEventListener) {
          document.addEventListener(
            'WeixinJSBridgeReady',
            vm.onBridgeReady(data),
            false
          )
        } else if (document.attachEvent) {
          document.attachEvent('WeixinJSBridgeReady', vm.onBridgeReady(data))
          document.attachEvent('onWeixinJSBridgeReady', vm.onBridgeReady(data))
        }
      } else {
        vm.onBridgeReady(data)
      }
    },
    onBridgeReady (data) {
      var vm = this
      // eslint-disable-next-line no-undef
      WeixinJSBridge.invoke(
        'getBrandWCPayRequest',
        {
          // 下面参数内容都是后台返回的
          debug: true,
          appId: data.appId, // 公众号名称，由商户传入
          timeStamp: data.timeStamp, // 时间戳
          nonceStr: data.nonceStr, // 随机串
          package: data.package, // 预支付id
          signType: data.signType, // 微信签名方式
          paySign: data.paySign // 微信签名
          // 'appId' => 'wx1b4b2f622534cd9e',
          // 'timeStamp' => '1584933336',
          // 'nonceStr' => 'xdEWHIzcgEjSt3Y36RVNRo9DNuDENM81',
          // 'package' => 'prepay_id=wx23111536216451914acfaf0b1128513200',
          // 'signType' => 'MD5',
          // 'paySign' => 'BEBC90A6562D2FBA477602C8CF6B3147',
        },
        function (res) {
          vm.showDialog = false
          // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
          if (res.err_msg === 'get_brand_wcpay_request:ok') {
            vm.$toast('支付完成', function () {
              vm.$emit('finished')
            })
          } else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
            vm.$toast('交易取消', function () {
              vm.$emit('cancel')
            })
          } else {
            // 支付失败
            vm.$toast('支付失败' + res.err_msg, function () {
              vm.$emit('finished')
            })
          }
        }
      )
    },
    // onClosePayment () {
    //   this.$emit('close', this.showDialog)
    // },
    onClickSku (item) {
      console.log('onClickSku', item.id)
      this.$emit('click-desc', item)
    },
    onChangeStepper (id, num) {
      this.$emit('change-stepper', id, num)
    },
    formatDescription (sku, stock) {
      if (stock > 0) {
        return sku
      }
      return sku + '（库存不足）'
    },
    formatPrice (price) {
      return price.toFixed(2)
    }
  }
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
.payment-dialog {
  padding: 54px 15px 15px;

  h1 {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 54px;
    margin: 0;
    text-align: center;
    font-size: 18px;
    line-height: 54px;
  }
  h2 {
    text-align: center;
    margin-top: 0;
  }
  .countdown {
    margin: 10px 0;
    text-align: center;
    &-container {
      padding: 3px 8px;
      background: #f0f0f0;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      border-radius: 99px;
    }
    &-title {
      font-size: 12px;
      color: #666;
      line-height: initial;
    }
    .van-count-down {
      font-size: 12px;
      color: #666;
      line-height: initial;
    }
  }
  .payment-paymodes {
    margin: 20px 0 100px;
  }
  /deep/ .van-cell {
    padding: 15px 5px;
    &__left-icon {
      font-size: 30px;
      margin-right: 10px;
      height: 100%;
    }
    &__title {
      font-size: 16px;
    }
    &__label {
      font-size: 10px;
      margin: 0;
    }
  }
}
</style>
